package basic.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerialTest {
	public static void main(String[] args) throws Exception {
		File file = new File("person.out");

		ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(
				file));
		Person person = new Person("John", 101, Gender.MALE);
		oout.writeObject(person);
		oout.close();

		ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));
		// 当重新读取被保存的Person对象时，并没有调用Person的任何构造器，看起来就像是直接使用字节将Person对象还原出来的
		Object newPerson = oin.readObject(); // 没有强制转换到Person类型
		oin.close();
		System.out.println(newPerson);
	}
}

/*
 * arg constructor [John, 101, MALE]
 */

enum Gender {
	MALE, FEMALE
}

class Person implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String name = null;

	// transient private Integer age = null; 序列化将忽略age
	private Integer age = null;

	private Gender gender = null;

	public Person() {
		System.out.println("none-arg constructor");
	}

	public Person(String name, Integer age, Gender gender) {
		System.out.println("arg constructor");
		this.name = name;
		this.age = age;
		this.gender = gender;
	}

	private void writeObject(ObjectOutputStream out) throws Exception {
		System.out.println("writeObject called!");
		out.defaultWriteObject();
	}

	private void readObject(ObjectInputStream in) throws Exception {
		System.out.println("readObject called!");
		in.defaultReadObject();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Gender getGender() {
		return gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "[" + name + ", " + age + ", " + gender + "]";
	}
}